﻿package {
	import grid.Grid;
	import grid.PositionData;

	import info.Info;

	import menu.MenuPopup;

	import objects.AbstractObject;

	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;

	[SWF(width="800", height="600", backgroundColor="0x999999")]
	public class Main extends Sprite {
		private static const PATH : String = "../DropBox/NeonThrust/Classes/Level";
		private static const KEY_DELETE : uint = 8;
		private static const KEY_R : uint = 82;
		private static const KEY_RETURN : uint = 13;
		private static const KEY_SPACE : uint = 32;
		private var _gridLines : Grid;
		private var _info : Info;
		private var _menu : MenuPopup;
		private var _code : TextField;

		public function Main() {
			_gridLines = new Grid();
			addChild(_gridLines);
			_info = new Info();
			addChild(_info);
			_menu = new MenuPopup(this);
			addChild(_menu);
			_code = new TextField();
			_code.x = 50;
			_code.y = 50;
			_code.width = 600;
			_code.height = 400;
			//_code.autoSize = TextFieldAutoSize.LEFT;
			_code.background = true;
			_code.border = true;
			_code.visible = false;
			addChild(_code);

			addEventListener(Event.ENTER_FRAME, onEnterFrame);
			stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);

			States.state = States.DRAW_NO_DAMAGE;

			toggleMenu();
		}

		public function toggleDiscreet() : void
		{
			_gridLines.alpha = (_gridLines.alpha == 1) ? _gridLines.alpha = .1 : _gridLines.alpha = 1;
		}


		public function updateGrid() : void {
			_gridLines.updateGrid();
		}

		public function loadImage(url : String) : void {
			_gridLines.loadImage(url);
		}

		private function onKeyDown(event : KeyboardEvent) : void {
			switch(event.keyCode) {
				case KEY_DELETE:
					undo();
					break;
				case KEY_R:
					reset();
					break;
				case KEY_RETURN:
					generateCode();
					break;
				case KEY_SPACE:
					toggleMenu();
					break;
			}
		}

		private function reset() : void {
			_gridLines.reset();
		}

		private function undo() : void {
			_gridLines.undo();
		}

		private function toggleMenu() : void {
			if (_menu.visible) {
				_gridLines.enable();
				_menu.visible = false;
				_code.visible = false;
			} else {
				_gridLines.disable();
				_menu.visible = true;
			}
		}

		private function generateCode() : void {
		}

		private function onEnterFrame(event : Event) : void {
			_info.setPointerPosition(_gridLines.getPointerPosition());
		}

		public function generate() : void {
			/***********************************************
			 * DIRECTORY
			 ***********************************************/
			var directory : File = File.desktopDirectory.resolvePath(PATH + _menu.getLevel());
			directory.createDirectory();

			/***********************************************
			 * LEVEL
			 ***********************************************/

			var level_h : String = "";
			var level_mm : String = "";
			
			level_h += "//\tNeonThrust\n";
			level_h += "//\n";
			level_h += "//\tCreated by Rob Thurston on 18/07/2011.\n";
			level_h += "//\tCopyright 2011 shiny-games. All rights reserved.\n\n";
			
			level_h += "#import \"cocos2d.h\"\n";
			level_h += "#import \"AbstractLevel.h\"\n";
			level_h += "#import \"Level" + _menu.getLevel() + "Background.h\"\n";
			level_h += "#import \"Level" + _menu.getLevel() + "Physics.h\"\n\n";
			level_h += "@interface Level" + _menu.getLevel() + " : AbstractLevel\n";
			level_h += "{\n";
			level_h += "}\n\n";
			level_h += "@end";

			
			level_mm += "//\tNeonThrust\n";
			level_mm += "//\n";
			level_mm += "//\tCreated by Rob Thurston on 18/07/2011.\n";
			level_mm += "//\tCopyright 2011 shiny-games. All rights reserved.\n\n";
			
			level_mm += "#import \"Level" + _menu.getLevel() + ".h\"\n\n";
			level_mm += "@implementation Level" + _menu.getLevel() + "\n\n";
			
			level_mm += "-(void) setupScores\n";
			level_mm += "{\n";
			level_mm += "\tself.bonusTimeLimit = 40;\n";
			level_mm += "\tself.escapeTime = 10;\n";
			level_mm += "}\n\n";
			
			level_mm += "-(void) setupBackground\n";
			level_mm += "{\n";
			level_mm += "\t_background = [Level" + _menu.getLevel() + "Background node];\n";
			level_mm += "\t[self addChild:_background];\n";
			level_mm += "}\n\n";
			level_mm += "-(void) setupPhysics\n";
			level_mm += "{\n";
			level_mm += "\t_physics = [[Level" + _menu.getLevel() + "Physics node] initWithGameController:_gameController];\n";
			level_mm += "\t[self addChild:_physics];\n";
			level_mm += "}\n\n";
			level_mm += "@end";

			var levelFile_h : File = File.desktopDirectory.resolvePath(PATH + _menu.getLevel() + "/Level" + _menu.getLevel() + ".h");
			var levelStream_h : FileStream = new FileStream();
			levelStream_h.open(levelFile_h, FileMode.WRITE);
			levelStream_h.writeUTFBytes(level_h);
			levelStream_h.close();

			var levelFile_mm : File = File.desktopDirectory.resolvePath(PATH + _menu.getLevel() + "/Level" + _menu.getLevel() + ".mm");
			var levelStream_mm : FileStream = new FileStream();
			levelStream_mm.open(levelFile_mm, FileMode.WRITE);
			levelStream_mm.writeUTFBytes(level_mm);
			levelStream_mm.close();

			/***********************************************
			 * BACKGROUND
			 ***********************************************/

			var levelBackground_h : String = "";
			var levelBackground_mm : String = "";

			levelBackground_h += "//\tNeonThrust\n";
			levelBackground_h += "//\n";
			levelBackground_h += "//\tCreated by Rob Thurston on 18/07/2011.\n";
			levelBackground_h += "//\tCopyright 2011 shiny-games. All rights reserved.\n\n";
			
			levelBackground_h += "#import \"cocos2d.h\"\n";
			levelBackground_h += "#import \"AbstractLevelBackground.h\"\n\n";
			levelBackground_h += "@interface Level" + _menu.getLevel() + "Background : AbstractLevelBackground \n";
			levelBackground_h += "{\n";
			levelBackground_h += "}\n\n";
			levelBackground_h += "@end";
			
			levelBackground_mm += "//\tNeonThrust\n";
			levelBackground_mm += "//\n";
			levelBackground_mm += "//\tCreated by Rob Thurston on 18/07/2011.\n";
			levelBackground_mm += "//\tCopyright 2011 shiny-games. All rights reserved.\n\n";

			levelBackground_mm += "#import \"Level" + _menu.getLevel() + "Background.h\"\n\n";
			levelBackground_mm += "@implementation Level" + _menu.getLevel() + "Background\n\n";
			levelBackground_mm += "-(id) init\n";
			levelBackground_mm += "{\n";
			levelBackground_mm += "\tif((self=[super initWithForeground:@\"Level" + _menu.getLevel() + ".tmx\" background:@\""+_menu.getZone()+"\"]))\n";
			levelBackground_mm += "\t{\n";
			levelBackground_mm += "\t}\n\n";
			levelBackground_mm += "\treturn self;\n";
			levelBackground_mm += "}\n\n";
			levelBackground_mm += "@end";

			var levelBackgroundFile_h : File = File.desktopDirectory.resolvePath(PATH + _menu.getLevel() + "/Level" + _menu.getLevel() + "Background.h");
			var levelBackgroundStream_h : FileStream = new FileStream();
			levelBackgroundStream_h.open(levelBackgroundFile_h, FileMode.WRITE);
			levelBackgroundStream_h.writeUTFBytes(levelBackground_h);
			levelBackgroundStream_h.close();

			var levelBackgroundFile_mm : File = File.desktopDirectory.resolvePath(PATH + _menu.getLevel() + "/Level" + _menu.getLevel() + "Background.mm");
			var levelBackgroundStream_mm : FileStream = new FileStream();
			levelBackgroundStream_mm.open(levelBackgroundFile_mm, FileMode.WRITE);
			levelBackgroundStream_mm.writeUTFBytes(levelBackground_mm);
			levelBackgroundStream_mm.close();

			/***********************************************
			 * PHYSICS
			 ***********************************************/

			var levelPhysics_h : String = "";

			levelPhysics_h += "//\tNeonThrust\n";
			levelPhysics_h += "//\n";
			levelPhysics_h += "//\tCreated by Rob Thurston on 18/07/2011.\n";
			levelPhysics_h += "//\tCopyright 2011 shiny-games. All rights reserved.\n\n";
			
			levelPhysics_h += "#import \"cocos2d.h\"\n";
			levelPhysics_h += "#import \"Box2D.h\"\n";
			levelPhysics_h += "#import \"AbstractLevelPhysics.h\"\n\n";
			levelPhysics_h += "@class GameController;\n\n";
			levelPhysics_h += "@interface Level" + _menu.getLevel() + "Physics : AbstractLevelPhysics\n";
			levelPhysics_h += "{\n";
			levelPhysics_h += "}\n\n";
			levelPhysics_h += "@end";

			var levelPhysicsFile_h : File = File.desktopDirectory.resolvePath(PATH + _menu.getLevel() + "/Level" + _menu.getLevel() + "Physics.h");
			var levelPhysicsStream_h : FileStream = new FileStream();
			levelPhysicsStream_h.open(levelPhysicsFile_h, FileMode.WRITE);
			levelPhysicsStream_h.writeUTFBytes(levelPhysics_h);
			levelPhysicsStream_h.close();

			var levelPhysicsFile_mm : File = File.desktopDirectory.resolvePath(PATH + _menu.getLevel() + "/Level" + _menu.getLevel() + "Physics.mm");
			var levelPhysicsStream_mm : FileStream = new FileStream();
			levelPhysicsStream_mm.open(levelPhysicsFile_mm, FileMode.WRITE);
			levelPhysicsStream_mm.writeUTFBytes(getPhisycs_mm());
			levelPhysicsStream_mm.close();
		}
		
		public function generateTileMap() : void
		{
			/***********************************************
			 * TILE MAPS
			 ***********************************************/
			
			var tileMapHD : String = "";
			tileMapHD += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
			tileMapHD += "<map version=\"1.0\" orientation=\"orthogonal\" width=\"80\" height=\"60\" tilewidth=\"32\" tileheight=\"32\">\n";
			tileMapHD += "<tileset firstgid=\"1\" name=\"TileMap-hd\" tilewidth=\"32\" tileheight=\"32\">\n";
			tileMapHD += "\t<image source=\"Zone"+_menu.getZone()+"TileMap-hd.png\" width=\"704\" height=\"512\"/>\n";
			tileMapHD += "</tileset>\n";
			tileMapHD += "<layer name=\"Tile Layer 1\" width=\"80\" height=\"60\">\n";
			tileMapHD += "\t<data encoding=\"base64\" compression=\"gzip\">\n";
			tileMapHD += "\t\t H4sIAAAAAAAAA+1cuU7EMBBNwVfwE7v/QIVAVDRUNICADtEBAiquakGwDcc/cHwgkyKSsTzxMYfHEZGexG4Oj9+cnnhZ7bpuNYIZ8v074MP5PE+8D/u+x1YXPrYz5HsFvGWOK3kdhm/AD/EZrgyngF2Evx3ASeB+X2c9PgFfkWtawSD7BuAugnvAA8LfDeA24RmbleZJtcUYh+sIL9zHmuA8uPnLuccKf5J2kgosPrfAX4nvcNulH59T7tXkzx03d/4ltqGhJ237i/kpdj7VNnK5H+MndM6Xr1X/zbERCvexcTX568eL+WHNmjA1h7nrE237821hTObSnCydy931Scv+q1XzzEbGssafNCd+fPB7Bbky1ODP0rqX0ivoebZmf1p2yAHL/KXKr8Uz1gPcA+wDDvio+nMcAo4Axxmycq41pGPFGeAccMFFmHdcAq4A1xkyUerdUD7AbJeDvwXgEfAEWBHAM+AFsGSUeQwp+YAih3+vb9/+GsGNMRzjxvyphbwRg+s/lP5jqi9ROAzFSqoOOOwlBTFbwnyptAcT0zUXf1qQzG1z4edzc019Nyipc+kxMT2V1lG1er3WEIoNKT4h1W/kQivxTWPuGrYe6zFK9Rmpek7hxqKt1+oP+eMO3FjtI2uNM6V4U1LTLwrPcWKZcH7QE3VNMXYtdW9VC7bEHRO158zZn6CgdP1cg4uZ93fovtR9mFzcavqadC0y8Fea28f0YbX+4n7OP+QhuZ6w9N5TCjn7M2qBIpOFnFY6Twu68HNa6f4dC3PRlEPL7qT3a9filOM3IbUh3evirBelZKfYhrV1XU494MsuEQ+mWJ9gdufGA+n3OC2D4jMhXn19WFujWtelxX49BVbqOAwccbbGO2srPE+h7moBtePVENensPegtGdMee4Q17niOzWvasQLLZsdm4uWDJrrH63/s6DJ4dTqnhL+pPbVW6/BuFDLhjj8cQp5lQslv3mT7P1o7BMvuR6DRE0ek23MfmusETB5OftqnHG1lfw36PIXF99izgBLAAA=\n";
			tileMapHD += "\t</data>\n";
			tileMapHD += "</layer>\n";
			tileMapHD += "</map>\n";

			var tileMapHD_tmx : File = File.desktopDirectory.resolvePath("../DropBox/NeonThrust/Resources/tilemaps/levels/Level" + _menu.getLevel() + "-hd.tmx");
			var tileMapHDStream_tmx : FileStream = new FileStream();
			tileMapHDStream_tmx.open(tileMapHD_tmx, FileMode.WRITE);
			tileMapHDStream_tmx.writeUTFBytes(tileMapHD);
			tileMapHDStream_tmx.close();
			
			var tileMap : String = "";
			tileMap += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
			tileMap += "<map version=\"1.0\" orientation=\"orthogonal\" width=\"80\" height=\"60\" tilewidth=\"16\" tileheight=\"16\">\n";
			tileMap += "<tileset firstgid=\"1\" name=\"TileMap-hd\" tilewidth=\"16\" tileheight=\"16\">\n";
			tileMap += "\t<image source=\"Zone"+_menu.getZone()+"TileMap.png\" width=\"352\" height=\"256\"/>\n";
			tileMap += "</tileset>\n";
			tileMap += "<layer name=\"Tile Layer 1\" width=\"80\" height=\"60\">\n";
			tileMap += "\t<data encoding=\"base64\" compression=\"gzip\">\n";
			tileMap += "\t\t H4sIAAAAAAAAA+1cuU7EMBBNwVfwE7v/QIVAVDRUNICADtEBAiquakGwDcc/cHwgkyKSsTzxMYfHEZGexG4Oj9+cnnhZ7bpuNYIZ8v074MP5PE+8D/u+x1YXPrYz5HsFvGWOK3kdhm/AD/EZrgyngF2Evx3ASeB+X2c9PgFfkWtawSD7BuAugnvAA8LfDeA24RmbleZJtcUYh+sIL9zHmuA8uPnLuccKf5J2kgosPrfAX4nvcNulH59T7tXkzx03d/4ltqGhJ237i/kpdj7VNnK5H+MndM6Xr1X/zbERCvexcTX568eL+WHNmjA1h7nrE237821hTObSnCydy931Scv+q1XzzEbGssafNCd+fPB7Bbky1ODP0rqX0ivoebZmf1p2yAHL/KXKr8Uz1gPcA+wDDvio+nMcAo4Axxmycq41pGPFGeAccMFFmHdcAq4A1xkyUerdUD7AbJeDvwXgEfAEWBHAM+AFsGSUeQwp+YAih3+vb9/+GsGNMRzjxvyphbwRg+s/lP5jqi9ROAzFSqoOOOwlBTFbwnyptAcT0zUXf1qQzG1z4edzc019Nyipc+kxMT2V1lG1er3WEIoNKT4h1W/kQivxTWPuGrYe6zFK9Rmpek7hxqKt1+oP+eMO3FjtI2uNM6V4U1LTLwrPcWKZcH7QE3VNMXYtdW9VC7bEHRO158zZn6CgdP1cg4uZ93fovtR9mFzcavqadC0y8Fea28f0YbX+4n7OP+QhuZ6w9N5TCjn7M2qBIpOFnFY6Twu68HNa6f4dC3PRlEPL7qT3a9filOM3IbUh3evirBelZKfYhrV1XU494MsuEQ+mWJ9gdufGA+n3OC2D4jMhXn19WFujWtelxX49BVbqOAwccbbGO2srPE+h7moBtePVENensPegtGdMee4Q17niOzWvasQLLZsdm4uWDJrrH63/s6DJ4dTqnhL+pPbVW6/BuFDLhjj8cQp5lQslv3mT7P1o7BMvuR6DRE0ek23MfmusETB5OftqnHG1lfw36PIXF99izgBLAAA=\n";
			tileMap += "\t</data>\n";
			tileMap += "</layer>\n";
			tileMap += "</map>\n";

			var tileMap_tmx : File = File.desktopDirectory.resolvePath("../DropBox/NeonThrust/Resources/tilemaps/levels/Level" + _menu.getLevel() + ".tmx");
			var tileMapStream_tmx : FileStream = new FileStream();
			tileMapStream_tmx.open(tileMap_tmx, FileMode.WRITE);
			tileMapStream_tmx.writeUTFBytes(tileMap);
			tileMapStream_tmx.close();
		}

		private function getPhisycs_mm() : String {
			var levelPhysics_mm : String = "";

			levelPhysics_mm += "//\tNeonThrust\n";
			levelPhysics_mm += "//\n";
			levelPhysics_mm += "//\tCreated by Rob Thurston on 18/07/2011.\n";
			levelPhysics_mm += "//\tCopyright 2011 shiny-games. All rights reserved.\n\n";
			
			levelPhysics_mm += "#import \"Level" + _menu.getLevel() + "Physics.h\"\n\n";
			levelPhysics_mm += "@implementation Level" + _menu.getLevel() + "Physics\n\n";
			levelPhysics_mm += "-(void) setupWorld\n";
			levelPhysics_mm += "{\n";
			levelPhysics_mm += "\tb2Vec2 gravity;\n";
			levelPhysics_mm += "\tgravity.Set(0.0f, -0.0f);\n";
			levelPhysics_mm += "\tbool doSleep = true;\n";
			levelPhysics_mm += "\t_world = new b2World(gravity, doSleep);\n";
			levelPhysics_mm += "}\n\n";
			
			levelPhysics_mm += "//-(void) closeHatch:(ccTime) dt\n";
			levelPhysics_mm += "//{\n";
			levelPhysics_mm += "//\t[super closeHatch:dt];\n";
			levelPhysics_mm += "//\t[self showHelp];\n";
			levelPhysics_mm += "//}\n\n";
			
			levelPhysics_mm += "//-(void) reactorCollected\n";
			levelPhysics_mm += "//{\n";
			levelPhysics_mm += "//\t[super reactorCollected];\n";
			levelPhysics_mm += "//}\n\n";
			
			levelPhysics_mm += "//-(void) showHelp\n";
			levelPhysics_mm += "//{\n";
			
			levelPhysics_mm += "//\tCGSize screenSize = [CCDirector sharedDirector].winSize;\n\n";
			levelPhysics_mm += "//\t[_gameController showHelp:@\"Message.\" pos:ccp(screenSize.width / 2, screenSize.height / 2) showArrow:false];\n";
			levelPhysics_mm += "//}\n\n";

			levelPhysics_mm += "-(void) setupObjects\n";
			levelPhysics_mm += "{\n";

			for each (var object : AbstractObject in _gridLines.getObjects()) {
				levelPhysics_mm += "\t" + object.getCode() + ";\n";
			}

			levelPhysics_mm += "}\n\n";

			levelPhysics_mm += "-(void) setupWalls\n";
			levelPhysics_mm += "{\n";
			levelPhysics_mm += "\t///////////////////////////;\n";
			levelPhysics_mm += "\t// DAMAGE;\n";
			levelPhysics_mm += "\t///////////////////////////;\n\n";
			levelPhysics_mm += "\tb2BodyDef groundBodyDef;\n";
			levelPhysics_mm += "\tgroundBodyDef.position.Set(0, 0);\n";
			levelPhysics_mm += "\t_wallBodyDamage = _world->CreateBody(&groundBodyDef);\n";
			levelPhysics_mm += "\tb2PolygonShape wallShapeDamage;\n\n";

			for each (var damagePositionData : PositionData in _gridLines.getDamagePositionDataValues()) {
				levelPhysics_mm += "\twallShapeDamage.SetAsEdge(b2Vec2(" + damagePositionData.startPosition.x + ".0f / PTM_RATIO, " + (_gridLines.getYOffset() - damagePositionData.startPosition.y) + ".0f / PTM_RATIO), b2Vec2(" + damagePositionData.endPosition.x + ".0f / PTM_RATIO, " + (_gridLines.getYOffset() - damagePositionData.endPosition.y) + ".0f / PTM_RATIO));\n";
				levelPhysics_mm += "\t_wallBodyDamage->CreateFixture(&wallShapeDamage,0);\n\n";
			}

			levelPhysics_mm += "\t///////////////////////////;\n";
			levelPhysics_mm += "\t// NO DAMAGE;\n";
			levelPhysics_mm += "\t///////////////////////////;\n\n";
			levelPhysics_mm += "\tb2BodyDef groundBodyDef2;\n";
			levelPhysics_mm += "\tgroundBodyDef2.position.Set(0, 0);\n";
			levelPhysics_mm += "\t_wallBodyNoDamage = _world->CreateBody(&groundBodyDef2);\n";
			levelPhysics_mm += "\tb2PolygonShape wallShapeNoDamage;\n\n";

			for each (var noDamagePositionData : PositionData in _gridLines.getNoDamagePositionDataValues()) {
				levelPhysics_mm += "\twallShapeNoDamage.SetAsEdge(b2Vec2(" + noDamagePositionData.startPosition.x + ".0f / PTM_RATIO, " + (_gridLines.getYOffset() - noDamagePositionData.startPosition.y) + ".0f / PTM_RATIO), b2Vec2(" + noDamagePositionData.endPosition.x + ".0f / PTM_RATIO, " + (_gridLines.getYOffset() - noDamagePositionData.endPosition.y) + ".0f / PTM_RATIO));\n";
				levelPhysics_mm += "\t_wallBodyNoDamage->CreateFixture(&wallShapeNoDamage,0);\n\n";
			}

			levelPhysics_mm += "}\n\n";

			levelPhysics_mm += "@end";

			return levelPhysics_mm;
		}

		public function viewCode() : void {
			_code.text = getPhisycs_mm();
			_code.visible = !_code.visible;
		}
	}
}
